package wx

import (
	"net/http"
	"simai_oa/controller"
	"simai_oa/model"
	"simai_oa/tool"

	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
)


var store = base64Captcha.DefaultMemStore

type LoginController struct {
	controller.BaseController // 继承BaseController
}

// Index
//	@Summary	微信登陆绑定账号(通过status是否是bind区分接口,非bind时只需要传微信code)
//	@Tags		微信-登录功能
//	@param		name	formData	string	false	"用户名"
//	@param		pwd		formData	string	false	"密码"
//	@param		keyid	formData	string	false	"验证码是对应key"
//	@param		base64s	formData	string	false	"验证码"
//	@Success	200		{string}	json{"code","message"}
//	@Router		/wx/login/index [POST]
func (con LoginController) Index(c *gin.Context) {

	
	//获取open_id
	open_id := tool.GetOpenId(c)
	if open_id == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 7,
			"msg": "error",
		})
		return
	}

	status := c.PostForm("status")   // bind 代表绑定账号密码 其他值代表不需绑定

	if status != "bind" {
		adminInfo := model.Admin{}

		ok := tool.Gdb.Where("open_id = ?", open_id).First(&adminInfo).Error
		if ok != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":   3,
				"result": "用户不存在",
			})
		} else {
			Id := uint(adminInfo.Id)
			tokenString, errs := tool.GenToken(Id, adminInfo.Name, adminInfo.Type, adminInfo.GameId, adminInfo.RoleName)
			if errs != nil {
				c.JSON(http.StatusOK, gin.H{
					"code":     1001,
					"err_info": "生成token错误",
				})
				return
			}
			adminInfo.Pwd = ""
			adminInfo.Salt = ""
			adminInfo.OpenId = ""
			c.JSON(http.StatusOK, gin.H{
				"code":   1,
				"result": adminInfo,
				"token":  tokenString,
			})
		}
		return
	}

	//获取post值
	name := c.DefaultPostForm("name", "0")
	password := c.PostForm("pwd")


	// CaptchaId := c.PostForm("keyid")
	// CaptchaCode := c.PostForm("base64s")
	// if CaptchaCode == "" || CaptchaId == "" {
	// 	c.JSON(http.StatusOK, gin.H{
	// 		"code":   21,
	// 		"result": "参数缺失",
	// 	})
	// 	return
	// }
	// //验证码验证
	// errVerify := store.Verify(CaptchaId, CaptchaCode, true)
	// if !errVerify {
	// 	c.JSON(http.StatusOK, gin.H{
	// 		"code":   2,
	// 		"result": "验证码错误",
	// 	})
	// 	return
	// }

	adminInfo := model.Admin{}
	//查询用户是否存在
	name_exist := tool.Gdb.Where("name = ?", name).First(&adminInfo).Error
	if name_exist != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":   4,
				"result": "该账号不存在",
			})
			return
	}

	if adminInfo.OpenId != "" {
		c.JSON(http.StatusOK, gin.H{
			"code":   5,
			"result": "该账号已绑定wx小程序",
		})
		return
	}

	kw := "_KW"
	pwd := tool.Md5string(password + kw)
	//验证用户密码是否正确
	err := tool.PasswordVerify(pwd, adminInfo.Pwd, adminInfo.Salt)
	//err == nil 验证正确

	if err == nil {
		Id := uint(adminInfo.Id)
		tokenString, errs := tool.GenToken(Id, adminInfo.Name, adminInfo.Type, adminInfo.GameId, adminInfo.RoleName)
		if errs != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":     1001,
				"err_info": "生成token错误",
			})
			return
		}
		OpenId := open_id.(string)
		// err = model.Updates(&adminInfo, map[string]interface{}{"open_id":OpenId})
		err = model.Updates(&adminInfo, model.Admin{OpenId: OpenId})
		if err != nil {
			controller.ResFail(c, "操作失败")
			return
		}
		
		adminInfo.Pwd = ""
		adminInfo.Salt = ""
		adminInfo.OpenId = ""
		c.JSON(http.StatusOK, gin.H{
			"code":   1,
			"result": adminInfo,
			"token":  tokenString,
		})

		admin_log := model.AdminLogs{}
		types := []string{"登陆", "添加", "修改", "删除"}
		admin_log.CreatedAt = tool.GetDate()
		admin_log.UpdatedAt = tool.GetDate()
		admin_log.Type = 0
		admin_log.ActType = types[0]
		admin_log.RunUrl = c.Request.RequestURI
		admin_log.Username = name
		admin_log.Remark = "微信小程序登录:" + name
		admin_log.UserIP = c.ClientIP()

		tool.Gdb.Create(&admin_log)

	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":   2,
			"result": err,
		})
	}
}
